/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\SystemSettings\StatementOfAccountConfig\EconomicBusinessConfig\index.tsx
 * @Date: 2022-03-16 16:38:17
 * @LastEditTime: 2022-04-13 11:55:44
 */
import UdSelect from '@/components/UdFormControls/UdSelect'
import { columnRenders, http, IUdColumn, UdFilter, UdModal, UdTable, UdToolbar } from '@/lib'
import { Button, message, Modal, Tooltip } from 'antd'
import React, { PureComponent } from 'react'
import AddHanderForm from './components/AddHanderForm'
import apis from '@/apis/StatementOfAccount'
import { getSessionStorage, setSessionStorage } from '@/utils/methods'
type Props = {
  brandList: ReadonlyArray<any>
}

type State = {
  conditions: any[]
  loading: boolean
  page: number
  size: number
  total: number
  dataSource: any[]
}

/** 新增经济业务项目入参 */
type EB_Params = {
  projectName: string
  remarks: string
  valueType: string
  id?: number
  [Key: string]: any
}

const CALC_TYPE = {
  0: '系统取值',
  1: '人工输入',
  2: '公式计算',
}

const HAND_TYPE = {
  '+': '加',
  '-': '减',
  '*': '乘',
  '/': '除',
}

export default class EconomicBusinessConfig extends PureComponent<Props, State> {
  private filterForm: any
  private brandList: ReadonlyArray<any> = this.props.brandList
  state: State = {
    conditions: [
      {
        label: '品牌公司',
        id: 'brandCode',
        initialValue: this.brandList[0].value,
        render: <UdSelect showSearch allowClear={false} options={this.brandList} />,
      },
    ],
    loading: false,
    page: 1,
    size: 10,
    total: 0,
    dataSource: [],
  }
  columns: IUdColumn<any>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '50px',
      render: (text, reoled, index) => index + 1,
    },
    {
      title: '经济业务项目名称',
      dataIndex: 'projectName',
      align: 'center',
      key: 'projectName',
      width: '230',
      render: (text, record) => {
        return (
          <Tooltip title={record.projectName}>
            <div style={{ width: '100%', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.projectName}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '取值逻辑',
      dataIndex: 'logicValue',
      align: 'center',
      key: 'logicValue',
      minWidth: '200px',
      render: (text, record) => {
        return (
          <Tooltip title={record.logicValue}>
            <div style={{ width: '100%', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.logicValue}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '描述',
      dataIndex: 'remarks',
      align: 'center',
      key: 'remarks',
      minWidth: '200px',
      render: (text, record) => {
        return (
          <Tooltip title={record.remarks}>
            <div style={{ width: '100%', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.remarks}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: '160px',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      fixed: 'right' as 'right',
      width: 130,
      render: columnRenders.operate([
        {
          title: '编辑',
          action: (text: any, record: any) => {
            this.handerDrawer(record.id)
          },
        },
        {
          title: '删除',
          action: (text: any, record: any) => {
            Modal.confirm({
              title: '删除',
              content: `确定删除【${record.projectName}】此项配置吗`,
              okType: 'danger',
              onOk: () => {
                return this.handDeleteEconomicBusiness(record.id)
              },
            })
          },
        },
      ]),
    },
  ]

  componentDidMount(): void {
    this.getRecordTableData()
    !getSessionStorage('FINANCIAL_FIELD') && this.getAllCalcEnum()
  }

  private getAllCalcEnum = () => {
    http.get(apis.getAllCalcEnum).then(res => {
      let { data = [] } = res
      setSessionStorage('FINANCIAL_FIELD', data)
    })
  }

  private handleSearch = (values: any) => {
    this.setState({ page: 1 }, () => {
      this.getRecordTableData()
    })
  }

  private resetFilterHandle = form => {
    this.setState(
      {
        dataSource: [],
        page: 1,
        total: 0,
      },
      () => {
        this.getRecordTableData()
      }
    )
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getRecordTableData()
    })
  }

  private getRecordTableData = async () => {
    this.setState({ loading: true })
    try {
      let list: any = await http.post(apis.getEconomicBusinessList, {
        page: this.state.page,
        size: this.state.size,
        conditions: this.filterForm.getFieldsValue(),
      })
      const dataSource = list.data?.content
      this.setState({
        dataSource,
        total: list.data.totalElements,
        loading: false,
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }

  private handAddEconomicBusiness = (params: EB_Params) => {
    return http
      .post(apis.addEconomicBusiness, params)
      .then(() => {
        message.success('操作成功')
        this.getRecordTableData()
      })
      .catch(() => {
        return Promise.reject()
      })
  }

  private handUpdateEconomicBusiness = (params: EB_Params) => {
    return http
      .post(apis.updateEconomicBusiness, params)
      .then(() => {
        message.success('编辑成功')
        this.getRecordTableData()
      })
      .catch(() => {
        return Promise.reject()
      })
  }

  private handDeleteEconomicBusiness = (id: number) => {
    return http
      .get(apis.deleteEconomicBusiness, { params: { id } })
      .then(() => {
        message.success('删除成功')
        this.getRecordTableData()
      })
      .catch(() => {
        return Promise.reject()
      })
  }

  private handerDrawer = (projectId?: number) => {
    UdModal.open({
      title: projectId ? '编辑' : '新增',
      width: '60%',
      content: <AddHanderForm calcType={CALC_TYPE} handType={HAND_TYPE} id={projectId} />,
      okText: '确定',
      cancelText: '取消',
      onOk: values => {
        console.log('values', values)
        let {
          projectName,
          remarks,
          valueType,
          valueResult,
          letterCalculationOn,
          calcFormula: { result = undefined, letterCalculationTw = [] } = {},
        } = values
        let params: EB_Params = {
          projectName,
          remarks,
          valueType,
          brandCode: this.filterForm.getFieldsValue()['brandCode'],
        }
        if (valueType === '0') {
          params['letterCalculationOn'] = [{ calculationOn: valueResult, calculationType: valueType }]
        } else if (valueType === '2') {
          params['letterCalculationOn'] = letterCalculationOn
          params['letterCalculationTw'] = letterCalculationTw
          params['result'] = result
        }
        if (projectId) {
          params['id'] = projectId
          return this.handUpdateEconomicBusiness(params)
        } else {
          return this.handAddEconomicBusiness(params)
        }
      },
    })
  }

  render() {
    const { loading, page, size, total, dataSource, conditions } = this.state
    return (
      <>
        <UdFilter
          items={conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          getForm={form => {
            this.filterForm = form
          }}
          loading={this.state.loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdToolbar
          other={
            <Button
              type="primary"
              onClick={() => {
                this.handerDrawer()
              }}
            >
              新增
            </Button>
          }
        ></UdToolbar>
        <UdTable
          rowKey="id"
          loading={loading}
          columns={this.columns}
          dataSource={dataSource}
          onChange={this.handleChangePage}
          scroll={{ x: true }}
          pagination={{
            current: page,
            pageSize: size,
            total: total,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </>
    )
  }
}
